package com.fablesoft.projectdatacollect;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.os.HandlerThread;
import android.util.Log;

import com.fablesoft.projectdatacollect.bean.LoginResponse;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.FileUtils;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.fablesoft.projectdatacollect.util.PreferencesUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyApplication extends Application {
    private static MyApplication instance;
    private static final String TAG = "MyApplication";
    private ExecutorService mThreadPool;
    private String sessionId = "";
    // private Activity mainActivity;
    // private static Stack<Activity> activityStack;
    private String cachePath;

    private String userType;

    private static String mLocalVersion;

    private boolean isLogin;

    private String username;

    private String orgId;

    private String rootPath;
    private HandlerThread handlerThread;

    private boolean isCheckUpdate = true;

    public String getRootPath() {
        return rootPath;
    }

    public HandlerThread getHandlerThread() {
        return handlerThread;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (instance == null) {
            instance = this;
        }
        mLocalVersion = localVersion();
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        initImageLoader(getApplicationContext());
        handlerThread = new HandlerThread("handlerThread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
        handlerThread.start();
        setRootPath();
    }

    public static MyApplication getInstance() {
        return instance;
    }

    private void setRootPath() {
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            rootPath = info.applicationInfo.dataDir;
            Log.i("luzx", "rootPath=" + rootPath);
        } catch (NameNotFoundException e) {
            Log4jUtil.e(e.toString());
            e.printStackTrace();
        }
    }

    public ExecutorService getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mThreadPool == null) {
            mThreadPool = Executors.newCachedThreadPool();
        }
        return mThreadPool;
    }

    /**
     * 初始化ImageLoader
     */
    public void initImageLoader(Context context) {
        String dirs = "/Android/data/" + context.getPackageName() + "/cache/";
        File cacheDir = StorageUtils.getOwnCacheDirectory(context, dirs);// 获取到缓存的目录地址
        cachePath = cacheDir.getPath();
        Log.d("cacheDir", cachePath);
        // 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context)
                // .memoryCacheExtraOptions(480, 800) // max width, max
                // height，即保存的每个缓存文件的最大长宽
                // .discCacheExtraOptions(480, 800, CompressFormat.JPEG,
                // 75, null) // Can slow ImageLoader, use it carefully
                // (Better don't use it)设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(6)
                // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                // .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024
                // * 1024)) // You can pass your own memory cache
                // implementation你可以通过自己的内存缓存实现
                .memoryCacheSize(20 * 1024 * 1024)
                // /.discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                // 将保存的时候的URI名称用MD5
                // 加密
                // .discCacheFileNameGenerator(new
                // HashCodeFileNameGenerator())//将保存的时候的URI名称用HASHCODE加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                // .discCacheFileCount(100) //缓存的File数量
                .discCache(new UnlimitedDiscCache(cacheDir))
                // 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(
                        new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout
                // (5
                // s),
                // readTimeout(30)// 超时时间
                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);// 全局初始化此配置
    }

    public void saveUserInfo(LoginResponse result) {
        if (result == null) {
            return;
        }
        // 保存到应用中s
        setUsername(result.getUserName());
        Log.i("luzx", "orgId:" + result.getOrgId());
        setOrgId(result.getOrgId());
        setUserType(result.getOrgBean().getType());
        setLogin(true);
    }

    public void clearUserInfo() {
        Editor editor = PreferencesUtil.getSharedPreferencesEditor(null);
        editor.putString("password", "");
        // 保存到应用中
        setLogin(false);
    }

    private String localVersion() {
        PackageManager pm = getApplicationContext().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
        } catch (NameNotFoundException e) {
            Log4jUtil.e(e.toString());
            e.printStackTrace();
        }
        String version = pi.versionName;
        System.out.println("version==============" + version);
        return version;
    }

    public static String getLocalVersion() {
        return mLocalVersion;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getCachePath() {
        return cachePath;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public void setLogin(boolean isLogin) {
        this.isLogin = isLogin;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public boolean isCheckUpdate() {
        return isCheckUpdate;
    }

    public void setCheckUpdate(boolean checkUpdate) {
        isCheckUpdate = checkUpdate;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    public String getUserType() {
        return userType;
    }

    public void setUserType(String userType) {
        this.userType = userType;
    }
}
